package com.rtx.wms.std.handler.qc.down;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.rtx.wms.std.po.bean.*;
import com.rtx.wms.std.qc.bean.RtxQc;
import com.rtx.wms.std.qc.bean.RtxQcDetail;
import com.rtx.wms.std.qc.service.RtxQcService;
import com.rtx.wms.std.transer.service.TransferService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.model.emums.SysNumberType;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.common.service.CommonService;
import com.rtx.wms.std.qc.bean.ApiQc;
import com.rtx.wms.std.qc.bean.ApiQcDetail;
import com.rtx.wms.std.qc.service.ApiQcService;
import com.rtx.wms.std.sku.bean.po.Sku;
import com.rtx.wms.std.sku.service.SkuService;
import com.rtx.wms.std.transer.bean.Transfer;
import com.rtx.wms.std.transer.bean.TransferDetail;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;

/**
 * 格瑞普 qc质检结果下发
 * @author Administrator
 *
 */
@SuppressWarnings("all")
@Component
public class QcToWmsHandle {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	ApiQcService apiQcService;
	
	@Autowired
	SkuService skuService;

	@Autowired
	RtxQcService rtxQcService;

	@Autowired
	private TransferService transferService;

	@Value("${riswms.zj.create:}")
	private String riswms_zj_create;
	
	/**
	 * 质检结果从中间表写入WMS
	 * @param whseid
	 */
	public void handlerQcToWms(){
		//获取中间表未处理成功的订单
		List<ApiQc> list = queryApiPo();
		if(CollectionUtils.isEmpty(list)){
			return;
		}
		for(ApiQc o : list){
			//添加wms入库单
			handelAddToWms(o);
			//更新中间表状态
			updateStatus(o);
		}
	}

	//获取中间表未处理成功的订单
	private List<ApiQc> queryApiPo() {
		LambdaQueryWrapper<ApiQc> qw = Wrappers.lambdaQuery();
		qw.in(ApiQc::getEdiflag, WmsConstant.DEFAULT_FLAG,WmsConstant.FAIL_FLAG);
		qw.lt(ApiQc::getRtxqueue, WmsConstant.DEFAULT_COUNT);
		return apiQcService.queryApiQcAndDetailBycondition("ris_edi", qw);
	}
	
	/**
	 * 写入wms
	 * @param o
	 */
	private void handelAddToWms(ApiQc aq) {
		String whseid = "";
		try {
			whseid = aq.getWhseid();
			
			String transferkey = commonService.getWmsKey(whseid, SysNumberType.SysNumberType11);

			RtxQc rtxQc = convertRtxQc(whseid,aq,transferkey);
			rtxQcService.insertRtxQcAndDetail(whseid,rtxQc);


			Transfer t = convertTransfer(whseid,aq,transferkey);
			transferService.insertTrnsferAndDetail(whseid,t);


			callWms(whseid,transferkey);
			aq.setEdiflag(WmsConstant.SUCCESS_FLAG);
		} catch (Exception e) {
			logger.error("仓库{}，批次号{}从中间表写入WMS异常",whseid,aq.getBatchid(),e);
			aq.setEdiflag(WmsConstant.FAIL_FLAG);
			aq.setEdimsg(e.getMessage());
		}
	};

	private RtxQc convertRtxQc(String whseid, ApiQc qc, String pokey) {
		RtxQc rtxQc = new RtxQc();
		BeanUtils.copyProperties(qc, rtxQc);

		List<RtxQcDetail> rtxQcDetailList = new ArrayList<RtxQcDetail>();

		double openqty = 0d;
		int i = 1;
		for(ApiQcDetail apd:qc.getDetails()) {
			RtxQcDetail pd = new RtxQcDetail();
			BeanUtils.copyProperties(apd,pd);
			pd.setWhseid(qc.getWhseid());
			pd.setRtxchecklist(qc.getRtxchecklist());
			pd.setEditwho("QMS");
			pd.setAddwho("QMS");
			pd.setRtxqc(" ");
			pd.setReceiptkey(qc.getReceiptkey());
			pd.setLineno(String.format("%05d", i++));
			rtxQcDetailList.add(pd);
		}
		rtxQc.setRtxQcDetailList(rtxQcDetailList);

		return rtxQc;

	}

	private Transfer convertTransfer(String whseid,ApiQc qc,String transferkey) {
		Transfer t = new Transfer();
		Double openqty = 0d;
		t.setWhseid(qc.getWhseid());
		t.setTransferkey(transferkey);
		t.setExterntransferkey(qc.getRtxchecklist());
		t.setWhseid(whseid);
		t.setStatus("02");
		t.setFromstorerkey("GREPOW");
		t.setTostorerkey("GREPOW");
		t.setType("LOT");
		t.setRtxerptype("309");
		t.setStatus("0");
		t.setAddwho("QMS");
		t.setEditwho("QMS");
		t.setAdddate(new Date());
		t.setEditdate(new Date());
		
		List<TransferDetail> pdList = new ArrayList<TransferDetail>();
		
		int i = 1;
		for(ApiQcDetail apd:qc.getDetails()) {
			double qty = 0d;
			double okqty = Double.parseDouble(Optional.ofNullable(apd.getOkqty()).orElse("0"));
			double ngqty = Double.parseDouble(Optional.ofNullable(apd.getNgqty()).orElse("0"));
			if(okqty > 0d) {
				qty = okqty;
			}else {
				qty = ngqty;
			}
			
			openqty = openqty + qty;
			TransferDetail td = new TransferDetail();
			td.setWhseid(whseid);
			td.setTransferlinenumber(String.format("%05d", i++));
			td.setFromstorerkey("GREPOW");
			td.setFrompackkey("STD");
			td.setFromlot(apd.getLot());
			td.setFromid("");
			td.setFromloc("");
			td.setFromuom("EA");
			td.setTostorerkey("GREPOW");
			td.setTopackkey("STD");
			td.setTouom("EA");
			td.setTolot(" ");
			td.setTransferkey(transferkey);
			td.setStatus("0");
			td.setFromsku(apd.getSku());
			td.setFromqty(qty+"");
			td.setTosku(apd.getSku());
			td.setToqty(qty+"");
			td.setAddwho("QMS");
			td.setEditwho("QMS");
			td.setAdddate(new Date());
			td.setEditdate(new Date());
			td.setLottable01(apd.getLottable01());
			td.setLottable02(apd.getLottable02());
			td.setLottable03(apd.getLottable03());

			try {
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
				LocalDate productDate = LocalDate.parse(apd.getLottable04(), formatter);
				LambdaQueryWrapper<Sku> lqw = Wrappers.lambdaQuery();
				lqw.eq(Sku::getSku, apd.getSku());
				lqw.eq(Sku::getSku, "GREPOW");
				List<Sku> skulist =skuService.selectSkuByWrapper(whseid, lqw);
				td.setLottable04(productDate);
				if(!CollectionUtils.isEmpty(skulist)) {
//					Long datecodedays =Long.parseLong(skulist.get(0).getDatecodedays());
//					td.setLottable11(productDate.plusDays(datecodedays));
				}
				
			} catch (Exception e) {
				throw e;
			}
			pdList.add(td);
		}
		t.setDetails(pdList);
		t.setOpenqty(openqty+"");
		
		
		return t;
		
	}
	
	void callWms(String whseid,String transferkey){
		String uid = UUID.randomUUID().toString();
		Map<String,String> request = new HashMap<>();
		request.put("transferkey", transferkey);
		request.put("whseid", whseid);
		request.put("hold", "N");
		logger.info("uid-{}-质检结果处理逻辑请求-{}",uid,JSON.toJSONString(request));
		String	result = HttpRequest
				.post(riswms_zj_create)
				.body(JSON.toJSONString(request))
				.timeout(30000)
				.execute()
				.body();
		logger.info("uid-{}-质检结果处理逻辑响应-{}",uid,result);
		JSONObject res = JSON.parseObject(result);
		if(!"200".equals(res.get("returnCode"))) {
			throw new RuntimeException("transferkey-"+transferkey+"-质检结果处理逻辑失败-"+result);
		}
	}
	
	/**
	 * 更新中间表状态
	 * @param o
	 */
	private void updateStatus(ApiQc o) {
		LambdaUpdateWrapper<ApiQc> update = Wrappers.lambdaUpdate();
		update.eq(ApiQc::getBatchid,o.getBatchid())
		.set(ApiQc::getEdiflag,o.getEdiflag())
		.set(ApiQc::getEdimsg,StrUtil.sub(o.getEdimsg(), 0, 498))
		.set(ApiQc::getRtxqueue,o.getRtxqueue() + 1);
		apiQcService.updStatus("ris_edi",update);
	};
	
}
